package com.ssy.file.service.utils;


import com.aliyun.oss.OSS;
import com.aliyun.oss.model.ListObjectsRequest;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.PutObjectResult;
import com.ssy.file.service.config.AliYunConfig;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.util.List;
import java.util.UUID;

@Component
public class AliyunOSSUtil {
    private static final Logger logger = LoggerFactory.getLogger(AliyunOSSUtil.class);
    private static final String HTTPS = "https://";

    @Autowired
    private AliYunConfig constantConfig;

    @Autowired
    OSS client;

    /**
     * 上传
     */
    public String upload(InputStream inputStream, String fileName) {
        String url = null;
        try {
            //切割文件名字
            if (StringUtils.isNotEmpty(fileName) && fileName.contains(".")) {
                String suffix = fileName.substring(fileName.lastIndexOf("."));
                fileName = fileName.substring(0, fileName.lastIndexOf("."));
                fileName = fileName.concat(UUID.randomUUID().toString().replace("-", "").concat(suffix));
            } else {
                fileName = fileName.concat(UUID.randomUUID().toString().replace("-", "").concat("."));
            }
            PutObjectResult putObjectResult = client.putObject(constantConfig.getBucketName(), fileName, inputStream);
            if (null != putObjectResult) {
                url = HTTPS + constantConfig.getBucketName() + "." + constantConfig.getWebUrl() + "/" + fileName;
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("文件上传异常", e);
        }

        return url;
    }


    /**
     * 根据文件url删除文件
     *
     * @author wrc
     * @date 2020/5/29
     */
    public void deleteFile(String filePath) {
        String[] split = filePath.split("\\/");
        filePath = split[split.length - 1];
        client.deleteObject(constantConfig.getBucketName(), filePath);
    }


    /**
     * 查看文件列表 包含指定前缀（prefix）的文件
     * maxKeys 文件查询数量
     * prefix 包含prefix前缀的文件
     * nextMarker 下一个标记
     * 文档链接 https://help.aliyun.com/document_detail/84841.html?spm=a2c4g.11186623.2.13.3ad5b5ddqxWWRu#concept-84841-zh
     *
     * @author wrc
     * @date 2020/5/29
     */
    public List<OSSObjectSummary> list(int maxKeys, String prefix, String nextMarker) {
        ObjectListing objectListing;
        List<OSSObjectSummary> sums = null;
        do {
            objectListing = client.listObjects(new ListObjectsRequest(constantConfig.getBucketName()).
                    withPrefix(prefix).withMarker(nextMarker).withMaxKeys(maxKeys));
            sums = objectListing.getObjectSummaries();
            nextMarker = objectListing.getNextMarker();

        } while (objectListing.isTruncated());
        return sums;
    }

}
